import React, { Component } from 'react'
import styles from "../assets/styles/tabA.module.css"
import Pageing from './UIComponent/Pageing'
import Model from './UIComponent/Model'

export default class TabA extends Component {
  state = {
    tableData: [
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2023-01-13 17:39:42",
          "2023-02-13 17:39:42"
        ],
        _id: "63919f95024a7602dc78082a",
        title: "测试优惠券",
        receiveType: "2",
        price: 30,
        state: false,
        show: false,
        system_data: true,
        create_time: "2022-12-08T08:25:57.209Z",
        imgSrc: "https://pic.616pic.com/ys_bnew_img/00/06/12/6QLoLGyq3C.jpg"
      },
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2022-01-13 17:39:42",
          "2024-01-13 17:39:42"
        ],
        _id: "63bd14c40d58511b7c6b6b18",
        title: "跨店满减",
        receiveType: "1",
        price: 200,
        state: true,
        show: true,
        create_time: "2023-01-10T07:33:24.011Z",
        imgSrc: "https://pic2.zhimg.com/v2-12943651b8b7fb48144151e638c8ed81_1440w.jpg?source=172ae18b"
      },
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2022-01-13 17:39:42",
          "2024-01-13 17:39:42"
        ],
        _id: "63bd14c40d58511b7c6b6b19",
        title: "新人券",
        receiveType: "2",
        price: 400,
        state: true,
        show: true,
        create_time: "2023-01-10T07:33:24.011Z",
        imgSrc: "https://pic2.zhimg.com/v2-12943651b8b7fb48144151e638c8ed81_1440w.jpg?source=172ae18b"
      },
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2022-01-13 17:39:42",
          "2024-01-13 17:39:42"
        ],
        _id: "63bd14c40d58511b7c6b6b20",
        title: "满100减20",
        receiveType: "3",
        price: 80,
        state: true,
        show: true,
        create_time: "2023-01-10T07:33:24.011Z",
        imgSrc: "https://pic2.zhimg.com/v2-12943651b8b7fb48144151e638c8ed81_1440w.jpg?source=172ae18b"
      },
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2022-01-13 17:39:42",
          "2022-01-15 17:39:42"
        ],
        _id: "63bd14c40d58511b7c6b6b21",
        title: "数码产品券",
        receiveType: "1",
        price: 60,
        state: true,
        show: true,
        create_time: "2023-01-10T07:33:24.011Z",
        imgSrc: "https://pic2.zhimg.com/v2-12943651b8b7fb48144151e638c8ed81_1440w.jpg?source=172ae18b"
      },
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2022-01-13 17:39:42",
          "2022-02-13 17:39:42"
        ],
        _id: "63bd14c40d58511b7c6b6b22",
        title: "跨店满减",
        receiveType: "2",
        price: 90,
        state: true,
        show: true,
        create_time: "2023-01-10T07:33:24.011Z",
        imgSrc: "https://pic2.zhimg.com/v2-12943651b8b7fb48144151e638c8ed81_1440w.jpg?source=172ae18b"
      },
      {
        time: [
          "2021-01-13 17:39:42",
          "2023-01-13 17:39:42"
        ],
        useTime: [
          "2022-01-13 17:39:42",
          "2022-01-13 17:39:42"
        ],
        _id: "63bd14c40d58511b7c6b6b23",
        title: "中秋现礼券",
        receiveType: "3",
        price: 10,
        state: true,
        show: true,
        create_time: "2023-01-10T07:33:24.011Z",
        imgSrc: "https://pic2.zhimg.com/v2-12943651b8b7fb48144151e638c8ed81_1440w.jpg?source=172ae18b"
      }
    ],
    searchType: "",
    searchData: "",
    status: 0,
    orderBy: 0,
    currentPage: 1,
    pageSize: 3,
    visible1: false,
    visible2: false,
    yname: "",
    yprice: "",
    ytype: "",
    ytime: [],
    ystate: "",
    product: {
    }
  }
  // filterData = []
  // filterTableData = []
  /**
   * React计算属性
   */
  get filterTableData() {
    /**
     * searchType:title
     * searchData:"优惠券"
     */
    const { tableData, searchType, searchData, orderBy } = this.state
    if (orderBy == 1) {
      tableData.sort((a, b) => {
        return b.price - a.price
      })
    } else {
      tableData.sort((a, b) => {
        return a.price - b.price
      })
    }
    // tableData.sort((a, b) => {
    //   return a.price - b.price
    // })
    // tableData.sort((a, b) => {
    //   return b.price - a.price
    // })
    //先排序，在进行筛选
    return tableData.filter(item => {
      if (!searchType && !searchData) {
        return true
      } else {
        if (item[searchType].indexOf(searchData) != -1) {
          return true
        }
      }
    })
  }

  /**
   * 过滤器
   * @param {} type 
   * @returns 
   */
  changeType = (type) => {
    switch (type) {
      case "1": return "新人券";
      case "2": return "门槛券";
      case "3": return "通用券";
      default:
        return "不详"
    }
  }
  /**
   * 修改日期
   * @param {} array 
   * @returns 
   */
  changeUseTime = (array) => {
    const begin = array[0]
    const end = array[1]
    const day1 = new Date(begin)
    const day2 = new Date(end)
    const diffDate = Math.abs(day1 - day2) / 1000 / 60 / 60 / 24
    return diffDate + "天"
  }
  /**
   * 下拉框的change绑定得到结果
   */
  typeChange = (event) => {
    const value = event.target.value;
    if (value == "title") {
      this.setState({
        searchType: value,
        status: 0
      })
    } else {
      this.setState({
        searchType: value,
        status: 1
      })
    }

  }
  /**
   * 文本框的change，获取输入值
   */
  textChange = (event) => {
    const value = event.target.value;
    this.setState({
      searchData: value
    })
  }
  /**
   * 用户根据下拉框选择 搜索类型
   * @param {} event 
   */
  userTypeChange = (event) => {
    const value = event.target.value
    this.setState({
      searchData: value
    })
  }
  sortByMax = () => {
    this.setState({
      orderBy: 1
    })
  }
  sortByMin = () => {
    this.setState({
      orderBy: 2
    })
  }

  deleteRow = (id) => {
    const { tableData } = this.state
    const index = tableData.findIndex(item => item._id == id)
    tableData.splice(index, 1)
    this.setState({
      tableData
    })
  }
  getCurrentPage = (page) => {
    console.log("父组件", page);
    this.setState({
      currentPage: page
    })
  }
  showMessage = (id) => {
    //根据id查询商品。回显
    const { tableData } = this.state
    const item = tableData.find(item => item._id == id)
    console.log(item);
    this.setState({
      product: item,
      visible2: true
    })
  }
  modelClose1 = () => {
    this.setState({
      visible1: false
    })
  }
  modelClose2 = () => {
    this.setState({
      visible2: false
    })
  }
  /**
   * 优惠券添加
   * @returns 
   */
  ynameChange = (event) => {
    const value = event.target.value;
    this.setState({
      yname: value
    })
  }

  ytypeChange = (event) => {
    // "true"
    // Boolean("false") false 
    const value = event.target.value;
    this.setState({
      ystate: JSON.parse(value)
    })
  }

  ytimeChange = (event) => {
    const value = event.target.value
    const { ytime } = this.state
    if (event.target.checked) {
      ytime.push(value)
    } else {
      const index = ytime.findIndex(item => item.ytime == value)
      ytime.splice(index, 1)
    }
    this.setState({
      ytime
    })
  }

  updateMsg = () => {
    const title = this.titleElement.value;
    const receiveType = this.typeElement.value;
    if (this.stateElement1.checked) {
      console.log(this.stateElement1.value);
    } else {
      console.log(this.stateElement2.value);
    }

    if (this.timeElement1.checked) {
      console.log(this.timeElement1.value);
    }
    if (this.timeElement2.checked) {
      console.log(this.timeElement2.value);
    }

    //将获取结果，用于覆盖product对象
    const {product,tableData} = this.state

    let newObj = {...product,title,receiveType}

    //替换tableData中原来的这个对象
    const index = tableData.findIndex(item=>item._id == newObj._id)
    tableData[index] = newObj

    this.setState({
      tableData
    })

  }
  render() {
    const { tableData, vari, status, pageSize, currentPage, visible1, visible2 } = this.state
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    return (
      <React.Fragment>
        <div className={styles.box}>
          <div className={styles.search}>
            <div>
              <select name="" id="" onChange={this.typeChange}>
                <option value="">请选择搜索类型</option>
                <option value="title">名字搜索</option>
                <option value="receiveType">类型搜索</option>
              </select>
            </div>
            <div>
              {status == 0 ?
                <input type="text" onChange={this.textChange} placeholder='输入搜索内容' /> :
                <select name="" id="" onChange={this.userTypeChange}>
                  <option value="">请选择类型</option>
                  <option value="1">新人券</option>
                  <option value="2">门槛券</option>
                  <option value="3">通用券</option>
                </select>
              }
            </div>
            <div>
              <button onClick={() => this.setState({ visible1: true })}>新增</button>
            </div>
          </div>
          <div className={styles.mytable}>
            <table>
              <thead>
                <tr>
                  <th>编号</th>
                  <th>优惠券名字</th>
                  <th>优惠券图片</th>
                  <th>优惠券类型</th>
                  <th>
                    <span>面值</span>
                    <span onClick={this.sortByMax}>&dArr;</span>
                    <span onClick={this.sortByMin}>&uArr;</span>
                  </th>
                  <th>使用事件</th>
                  <th>是否开启</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {this.filterTableData.slice(start, end).map(item => {
                  return (
                    <tr key={item._id}>
                      <td>{item._id}</td>
                      <td>{item.title}</td>
                      <td>
                        <img width="50px" src={item.imgSrc} alt="" />
                      </td>
                      <td>{this.changeType(item.receiveType)}</td>
                      <td>{item.price}</td>
                      <td>{this.changeUseTime(item.useTime)}</td>
                      <td>{item.state ? "开启" : "关闭"}</td>
                      <td>
                        <button onClick={() => this.deleteRow(item._id)}>删除</button>
                        <button onClick={() => this.showMessage(item._id)}>修改</button>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
          <div>
            <Pageing
              parentGetPage={this.getCurrentPage}
              total={this.filterTableData.length}
              currentPage={currentPage}
              pageSize={pageSize}>
            </Pageing>
          </div>
        </div>
        {/* 添加优惠券的模态框 */}
        <Model title="添加优惠券" close={this.modelClose1} visible={visible1}>
          {/* 插槽的概念 */}
          <div className='item'>
            <label htmlFor="">优惠券名字：</label>
            <input type="text" onChange={this.ynameChange} value={this.state.yname} placeholder='请输入优惠券名字' />
          </div>
          <div className='item'>
            <label htmlFor="">优惠券价格：</label>
            <input type="text" onChange={(e) => this.setState({ yprice: e.target.value })} value={this.state.yprice} />
          </div>
          <div className='item'>
            <label htmlFor="">优惠券类型：</label>
            <select name="" id="" onChange={(e) => this.setState({ ytype: e.target.value })} value={this.state.ytype}>
              <option value="">请选择</option>
              <option value="1">新人券</option>
              <option value="2">门槛券</option>
              <option value="3">通用券</option>
            </select>
          </div>
          <div className='item'>
            <label htmlFor="">优惠券状态：</label>
            <span>开启</span>
            <input type="radio" onChange={this.ytypeChange} value={true} name='state' />
            <span>关闭</span>
            <input type="radio" onChange={this.ytypeChange} value={false} name='state' />
          </div>
          <div>
            <label htmlFor="">日期:</label>
            <span>2023-01-02</span>
            <input type="checkbox" onChange={this.ytimeChange} value="2023-01-02" />
            <span>2023-04-02</span>
            <input type="checkbox" onChange={this.ytimeChange} value="2023-04-02" />
          </div>
          <div className='item'>
            <button>添加</button>
          </div>
        </Model>
        {/* 修改优惠券模态框 */}
        <Model title="修改优惠券" close={this.modelClose2} visible={visible2}>
          <div className='item'>
            <label htmlFor="">优惠券名字：</label>
            <input ref={element => this.titleElement = element} defaultValue={this.state.product.title} type="text" placeholder='请输入优惠券名字' />
          </div>
          <div className='item'>
            <label htmlFor="">优惠券类型：</label>
            <select ref={element => this.typeElement = element} name="" id="" defaultValue={this.state.product.receiveType}>
              <option value="">请选择</option>
              <option value="1">新人券</option>
              <option value="2">门槛券</option>
              <option value="3">通用券</option>
            </select>
          </div>
          <div className='item'>
            <label htmlFor="">优惠券状态：</label>
            <span>开启</span>
            <input type="radio" ref={element => this.stateElement1 = element} defaultChecked={this.state.product.state == true} value={true} name='state' />
            <span>关闭</span>
            <input type="radio" ref={element => this.stateElement2 = element} defaultChecked={this.state.product.state == false} value={false} name='state' />
          </div>
          <div>
            <label htmlFor="">日期:</label>
            <span>2023-01-02</span>
            <input type="checkbox" ref={element => this.timeElement1 = element} defaultChecked={this.state.product.useTime?.includes("2023-01-13 17:39:42")} value="2023-01-13 17:39:42" />
            <span>2023-04-02</span>
            <input type="checkbox" ref={element => this.timeElement2 = element} defaultChecked={this.state.product.useTime?.includes("2023-02-13 17:39:42")} value="2023-02-13 17:39:42" />
          </div>
          <div>
            <button onClick={this.updateMsg}>修改</button>
          </div>
        </Model>
      </React.Fragment>
    )
  }
}
